package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140"); // wht6.cn
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        Channel c = con.createChannel();
/*
        参数：
           1.队列名
           2.是否是持久队列
           3.是否是独占队列、排他队列
           4.是否自动删除
           5.其他属性配置
         */
        // false,false,false --- 非持久,非独占,不自动删除
        c.queueDeclare("task-queue",true,false,false,null);

        //创建回调对象
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到： "+s);
                for (int i = 0; i < s.length(); i++) {
                    if ('.' == s.charAt(i)) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
                //发送消息回执
                //c.basicAck(回执信息，是否要确认收到过的所有消息)
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                System.out.println("-------消息处理完成-------");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {


            @Override
            public void handle(String consumerTag) throws IOException {
            }
        };

        //每次抓取1条消息，处理完之前不抓取下一条
        c.basicQos(1);


        //接收、消费消息
        /*
        第二个参数：true  ， autoAck=true自动ack，自动确认
                            autoAck=false手动ack，手动确认，消费者手动发送回执
         */
        c.basicConsume("task-queue", false, deliverCallback, cancelCallback);
    }
}
